﻿using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace EcoSystem.EntityFrameworkCore
{
    /// <summary>
    /// Object对象值转换器
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ObjectValueConverter<T> : ValueConverter<T, string> where T : new()
    {
        private static JsonSerializerSettings settings = new JsonSerializerSettings()
        {
            NullValueHandling = NullValueHandling.Ignore,
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };

        public ObjectValueConverter()
             : base((Expression<Func<T, string>>)((T d) => SerializeObject(d)),
                   (Expression<Func<string, T>>)((string s) => DeserializeObject(s)), (ConverterMappingHints)null)
        {

        }

        private static string SerializeObject(T data)
        {

            T item = data ?? new T();
            return JsonConvert.SerializeObject(item, settings);
        }

        private static T DeserializeObject(string extraPropertiesAsJson)
        {
            if (extraPropertiesAsJson.IsNullOrEmpty() || extraPropertiesAsJson == "[]" || extraPropertiesAsJson == "{}")
            {
                return new T();
            }
            T result = JsonConvert.DeserializeObject<T>(extraPropertiesAsJson, settings);
            if (result == null) { result = new T(); }
            else
            {
                result.ConvertJObjectDictonary();
            }
            return result;
        }
    }
}
